package com.example.flowerpcback.services;

import com.example.flowerpcback.dto.Document;
import com.example.flowerpcback.dto.DocumentExample;
import com.example.flowerpcback.dto.Roles;
import com.example.flowerpcback.dto.RolesExample;
import com.example.flowerpcback.mapper.DocumentMapper;
import com.example.flowerpcback.req.DocumentReq;
import com.example.flowerpcback.req.RolesReq;
import com.example.flowerpcback.resp.DocumentResp;
import com.example.flowerpcback.resp.PageResp;
import com.example.flowerpcback.resp.RolesResp;
import com.example.flowerpcback.utils.CopyUtil;
import com.example.flowerpcback.utils.SnowFlake;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
public class DocumentService {
    private static final Logger LOG = LoggerFactory.getLogger(DocumentService.class);

    @Resource
    private DocumentMapper documentMapper;

    @Resource
    private SnowFlake snowFlake;

    public Document save(DocumentReq req){

        Document document = new CopyUtil().copy(req, Document.class);
        if(req.getId() == null){
            document.setCreateTime(new Date());
            document.setUpdateTime(new Date());
            Long id = snowFlake.nextId();
            document.setId(id);
            documentMapper.insert(document);
        }else {
            document.setUpdateTime(new Date());
            documentMapper.updateByPrimaryKeySelective(document);
        }

        return document;

    }

    public PageResp<DocumentResp> list(DocumentReq req) {
        DocumentExample documentExample = new DocumentExample();
        DocumentExample.Criteria criteria = documentExample.createCriteria();
        if(req.getName() != null) {
            criteria.andNameLike("%" + req.getName() + "%");
        }

        if(req.getKnowledgeId() != null) {
            criteria.andKnowledgeIdEqualTo(req.getKnowledgeId());
        }

        PageHelper.startPage(req.getPage(),req.getSize());
        List<Document> documentList = documentMapper.selectByExample(documentExample);
        List<DocumentResp> documentRespList = new CopyUtil().copyList(documentList, DocumentResp.class);
        PageInfo<DocumentResp> pageInfo = new PageInfo<>(documentRespList);
        PageResp<DocumentResp> pageResp = new PageResp<>();
        pageResp.setTotal(pageInfo.getTotal());
        pageResp.setPages(pageInfo.getPages());


        pageResp.setList(documentRespList);
        return pageResp;
    }


    public void delete(DocumentReq req){
        documentMapper.deleteByPrimaryKey(req.getId());
    }

}
